package com.glodon.paas.document.web.resource;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.glodon.paas.account.api.bean.User;
import com.glodon.paas.consts.StringConst;
import com.glodon.paas.document.api.bean.File;
import com.glodon.paas.document.service.FileService;
import com.glodon.paas.document.service.ShareService;
import com.glodon.paas.document.service.util.WebService;
import com.glodon.paas.exception.PaasServerException;
import com.glodon.paas.exception.PaasServerExceptionFactory;
import com.glodon.paas.util.StringUtil;
import com.glodon.paas.web.resource.BaseResource;

public abstract class ShareResource implements BaseResource {

    @Autowired
    private ShareService shareService;

    @Autowired
    private FileService  fileService;
    
    @Autowired
    private WebService webService;

    @POST
    @Path("/{fileId:.+}")
    @Produces(MediaType.APPLICATION_JSON)
    public List<User> shareFile(@Context
    HttpServletRequest request, @PathParam("fileId")
    String fileId, @QueryParam("type")
    String type, @QueryParam("sharer")
    String sharer, @QueryParam("privilege")
    String privilege) {
        String userId = getUserId(request);
        if (StringUtils.isEmpty(type)) {
            throw PaasServerExceptionFactory.unImplementedException("please add [type=id] in query paramter", null);
        } else if (StringUtils.isEmpty(sharer)) {
            throw PaasServerExceptionFactory.validateException("sharer is empty.", null);
        } else {
            List<User> shares = new ArrayList<User>();
            if (StringUtils.isNotEmpty(sharer)) {
                String[] ses = sharer.split(StringConst.SEPARATOR_COMMA);
                for (String se : ses) {
                    try {
                        shares.add(shareService.shareFile(userId, fileId, se, privilege));
                    } catch (PaasServerException e) {
                        getLoger().warn("share file[id:" + fileId + "] for user[" + se + "] failed. msg:["
                                                + e.getMessage() + "]");
                    }
                }
            }
            return shares;
        }
    }

    @GET
    @Path("/incoming")
    @Produces(MediaType.APPLICATION_JSON)
    public List<File> getRootFilesForMe(@Context
    HttpServletRequest request, @QueryParam("meta")
    String meta) {
        String userId = getUserId(request);
        if (meta == null) {
            throw PaasServerExceptionFactory.unImplementedException("please add meta in query paramter", null);
        } else {
            return shareService.getFilesByShares(shareService.getSharesForMe(userId), null, null, false);
        }
    }

    @GET
    @Path("/outcoming")
    @Produces(MediaType.APPLICATION_JSON)
    public List<File> getRootFilesByMe(@Context
    HttpServletRequest request, @QueryParam("meta")
    String meta) {
        String userId = getUserId(request);
        if (meta == null) {
            throw PaasServerExceptionFactory.unImplementedException("please add meta in query paramter", null);
        } else {
            return shareService.getFilesByShares(shareService.getSharesByMe(userId), null, null, false);
        }
    }

    @GET
    @Path("/{fileId:.+}")
    @Produces(MediaType.APPLICATION_JSON)
    public Object getShare(@Context
    HttpServletRequest request, @PathParam("fileId")
    String fileId, @QueryParam("type")
    String type, @QueryParam("meta")
    String meta, @QueryParam("sharer")
    String sharer, @QueryParam("child")
    String child) {
        String userId = getUserId(request);
        if (StringUtils.isEmpty(type)) {
            throw PaasServerExceptionFactory.unImplementedException("please add [type=id] in query paramter", null);
        } else if ((meta != null && sharer != null) || (meta != null && child != null)
                   || (sharer != null && child != null)) {
            throw PaasServerExceptionFactory.externalAPIException("too many paramters, [meta,child,sharer] just can be selected one or no.",
                                                                  null);
        } else if (meta != null) {
            return fileService.getFile(userId, fileId, false);
        } else if (sharer != null) {
            return shareService.getSharedUser(userId, fileId);
        } else if (child != null) {
            return fileService.getFiles(userId, fileId, null, null, false);
        } else {
            throw PaasServerExceptionFactory.externalAPIException("please appoint one paramter from [meta,sharer,child].",
                                                                  null);
        }
    }

    @DELETE
    @Path("/{fileId:.+}")
    @Produces(MediaType.TEXT_PLAIN)
    public String cancelShareFile(@Context
    HttpServletRequest request, @PathParam("fileId")
    String fileId, @QueryParam("type")
    String type, @QueryParam("sharer")
    String sharer) {
        String userId = getUserId(request);
        if (StringUtils.isEmpty(type)) {
            throw PaasServerExceptionFactory.validateException("please add [type=id] in query paramter", null);
        } else if (sharer != null) {
            String[] sharers = sharer.split(StringConst.SEPARATOR_COMMA);
            for (String sh : sharers) {
                if (StringUtil.isEmail(sh) || StringUtil.isMobile(sh)) {
                    User toUser = webService.getUser(sh);
                    if (toUser != null) {
                        sh = toUser.getId();
                    }
                }
                shareService.cancelShare(userId, fileId, sh);
            }
        } else {
            shareService.cancelShare(userId, fileId);
        }
        return StringConst.SUCCESS;
    }
}
